package com.ansion.basedb.dao.model;

import android.text.TextUtils;

import com.ansion.basedb.dao.LoginedUserMgr;
import com.ansion.log.VLog;
import com.ansion.string.StringUtils;
import com.ansion.utils.ContactUtil;
import com.ansion.utils.ImageUrlValidator;
import com.ansion.utils.image.ImageManager;

import org.json.JSONException;
import org.json.JSONObject;

//todo remove same field of uid
public class UserModel extends BaseModel implements Cloneable {
    public static final String TAG = "UserModel";
    public static final String LOCALCONTACTAVATARSCHEME = "contactAvatar";
    public static final String kColumnName_UserId = "userId";
    public static final String kColumnName_UCId = "ucid"; // payby专用id
    public static final String kColumnName_OAID = "oaid"; // 公众号专用id
    public static final String kColumnName_Alias = "alias";
    public static final String kColumnName_NickName = "nickName";
    public static final String kColumnName_AvatarUrl = "avatarUrl";
    public static final String kColumnName_AvatarPrevUrl = "avatarPrevUrl";
    public static final String kColumnName_CountryCode = "countryCode";
    public static final String kColumnName_Phone = "phone";
    public static final String kColumnName_Note = "note";
    public static final String kColumnName_UpdateTime = "updateTime";
    public static final String kColumnName_BackGround = "background";
    public static final String kColumnName_Status = "status";
    public static final String kColumnName_Status_Type = "status_type";
    public static final String kColumnName_Is_VIP = "isVip";
    public static final String kColumnName_VipExpireDate = "vipExpireDate";

    public static final String kColumnName_isStranger = "isStranger";//是否陌生人
    public static final String kColumnName_Is_OaVerified = "isOaVerified";
    public static final String kColumnName_OaIcon = "oaIcon";
    public static final String kColumnName_OaSubType = "oaSubType";
    public static final String kColumnName_extraData = "extraData";
    public static final int INVALID_ID = -1;
    public static final int STATUS_TYPE_SYS = 0; // 签名类型，0代表系统签名，1代表自定义签名
    public static final int STATUS_TYPE_CUSTOM = 1;
    public static final int STATUS_TYPE_NONE = 2;

    public final static String NO_NEED_UPDATE_VALUE = "!~no_)update(_value!~";
    // 用户内部唯一号 countrycode+phone
    @DatabaseField(columnName = kColumnName_UserId, index = true, unique = true, canBeNull = false)
    private long userId;
    @DatabaseField(columnName = kColumnName_UCId, index = true)
    private String ucid;
    @DatabaseField(columnName = kColumnName_OAID)
    private String oaid;
    @DatabaseField(columnName = kColumnName_Alias)
    private String alias;
    @DatabaseField(columnName = kColumnName_NickName)
    private String nickName;
    @DatabaseField(columnName = kColumnName_AvatarUrl)
    private String avatarUrl;
    @DatabaseField(columnName = kColumnName_CountryCode)
    private String countryCode;
    @DatabaseField(columnName = kColumnName_Phone)
    private String countryPhone;
    @DatabaseField(columnName = kColumnName_AvatarPrevUrl)
    private String avatarPrevUrl;
    @DatabaseField(columnName = kColumnName_Note)
    private String note;
    // 用于记录上次同步服务器的时间,单位 s
    @DatabaseField(columnName = kColumnName_UpdateTime)
    private long updateTime;
    @DatabaseField(columnName = kColumnName_BackGround)
    private String background;
    @DatabaseField(columnName = kColumnName_Status)
    private int status;
    @DatabaseField(columnName = kColumnName_Status_Type)
    private int status_type;
    @DatabaseField(columnName = kColumnName_Is_VIP)
    private boolean isVip;
    @DatabaseField(columnName = kColumnName_VipExpireDate)
    private long vipExpireDate;

    @DatabaseField(columnName = kColumnName_isStranger)
    private boolean isStranger;

    @DatabaseField(columnName = kColumnName_Is_OaVerified)
    private boolean oaVerified;

    @DatabaseField(columnName = kColumnName_OaIcon)
    private String oaIcon;

    @DatabaseField(columnName = kColumnName_OaSubType)
    private int oaSubType;

    @DatabaseField(columnName = kColumnName_extraData)
    private String extraData;
    private String email;//只有当前登录用户使用，不存入数据库

    private boolean isOnlyLocal;
    private ContactsModel contactModel;

    private String avatarDisplayText;

    private String lastContactNameHash;
    private UserModelExtra mUserModelExtra;

    public String getOaid() {
        return oaid;
    }

    public void setOaid(String oaid) {
        this.oaid = oaid;
    }

    public String getUcid() {
        return ucid;
    }

    public void setUcid(String ucid) {
        this.ucid = ucid;
    }

    public long getUserId() {
        return userId;
    }

    public void setUserId(long userId) {
        this.userId = userId;
    }

    public String getAlias() {
        return alias;
    }

    public void setAlias(String alias) {
        this.alias = alias;
    }

    public String getNickName() {
        return nickName;
    }

//	public String getContactName() {
//		if (null == contactModel) {
//			return null;
//		}
//		String firstName = contactModel.getFirstName();
//		String lastName = contactModel.getLastName();
//		if (!TextUtils.isEmpty(firstName) && !TextUtils.isEmpty(lastName)) {
//			return firstName + " " + lastName;
//		} else if (!TextUtils.isEmpty(firstName)) {
//			return firstName;
//		} else if (!TextUtils.isEmpty(lastName)) {
//			return lastName;
//		} else {
//			return "";
//		}
//	}

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }


    // public void setContactName(String nickName) {
    // this.nickName = nickName;
    // }

//    public String getName() {
//        return getNickName();
//    }

    public String getShortName() {

        String shorName = "";
        String firstName = null;
        String lastName = null;
        if (null != contactModel) {
            firstName = contactModel.getFirstName();
            lastName = contactModel.getLastName();
        }
        // if (alias != null && alias.trim().length() > 0) {
        // return getShortName(alias.trim().split(" "));
        // } else if (nickName != null && nickName.trim().length() > 0) {
        // return getShortName(nickName.trim().split(" "));
        // } else
        if (!TextUtils.isEmpty(firstName) && firstName.trim().length() > 0
                && !TextUtils.isEmpty(lastName) && lastName.trim().length() > 0) {
            if (StringUtils.isContainsChinese(firstName)
                    || StringUtils.isContainsChinese(lastName)) {
                shorName = lastName.trim().charAt(0) + "";
            } else {
                shorName = firstName.trim().charAt(0) + "" + lastName.trim().charAt(0);
            }
        } else if (!TextUtils.isEmpty(firstName)
                && firstName.trim().length() > 0) {
            shorName = firstName.trim().charAt(0) + "";
        } else if (!TextUtils.isEmpty(lastName) && lastName.trim().length() > 0) {
            shorName = lastName.trim().charAt(0) + "";
        } else {
            shorName = "";
        }
        if (TextUtils.isEmpty(shorName)) {
            shorName = "+";
            CurrentUser currentUser = LoginedUserMgr.getCurrentLoginedUser();
            if (ContactUtil.isSelf(String.valueOf(getUserId()))) {
                shorName = currentUser.getNickName();
                shorName = TextUtils.isEmpty(shorName) ? "+" : shorName.charAt(0) + "";
            }
            return shorName;
        } else
            return shorName.toUpperCase();
    }

    public String getShortNameForGroup() {
        String shortName = getShortName();
        if (TextUtils.isEmpty(shortName) || shortName.equals("+")) {
            shortName = getNickName();
            shortName = TextUtils.isEmpty(shortName) ? "+" : shortName.charAt(0) + "";
        }
        return shortName;
    }

//	private String getShortName(String[] shotSplit) {
//		String b = "";
//		for (int i = 0; i < shotSplit.length; i++) {
//			if (!TextUtils.isEmpty(shotSplit[i])) {
//				b = b + shotSplit[i].charAt(0);
//			}
//			if (b.length() > 1) {
//				return b;
//			}
//		}
//		return b;
//	}

    public String getAvatarUrl() {
        return avatarUrl;
    }

    /**
     * setAvatarPrevUrl 调用的地方太多了，容易漏掉
     * 其生成依赖于 avatarUrl，故放在一个方法里。
     */
    public void setAvatarUrl(String avatarUrl) {
        this.avatarUrl = avatarUrl;
        if (ImageUrlValidator.isImageUrl(avatarUrl)) {
            this.avatarPrevUrl = ImageManager.getAvatarPreUrl(avatarUrl);
        } else {
            this.avatarPrevUrl = "";
        }
    }

    public String getCountry() {
        return countryCode;
    }

    private int countrycodeInt = -1;

    public int getCountryInt() {
        countrycodeInt = ContactUtil.getCountryInt(countrycodeInt, String.valueOf(userId), countryCode);
        return countrycodeInt;
    }

    public void setCountry(String countryCode) {
        this.countryCode = countryCode;
    }

    public String getCountryPhone() {
        return countryPhone;
    }

    public void setCountryPhone(String countryPhone) {
        this.countryPhone = countryPhone;
    }

    /**
     * 此方法仅用于公众号相关逻辑，其余情况不可用。
     * 此方法仅用于公众号相关逻辑，其余情况不可用。
     * 此方法仅用于公众号相关逻辑，其余情况不可用。
     * <p>
     * 如果一定要使用，需要在 setAvatarUrl 之后调用。
     *
     * @param avatarPrevUrl 缩略图url
     */
    public void setAvatarPrevUrl(String avatarPrevUrl) {
        this.avatarPrevUrl = avatarPrevUrl;
    }

    public String getAvatarPrevUrl() {
        return buildAvatarPrevUrl(avatarUrl);
    }

    /**
     * 根据原图url构建缩略图url
     *
     * @param avatarUrl originalAvatar
     */
    private String buildAvatarPrevUrl(String avatarUrl) {
        if (TextUtils.isEmpty(avatarPrevUrl) && ImageUrlValidator.isImageUrl(avatarUrl)) {
            avatarPrevUrl = ImageManager.getAvatarPreUrl(avatarUrl);
        }
        return avatarPrevUrl;
    }

    public int getContactId() {
        if (null != contactModel) {
            return contactModel.getContactId();
        }
        return 0;
    }

    public String getNote() {

        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    /**
     * 使用的时候一定要找吴迪同步
     */
    public long getUpdateTime() {
        return updateTime;
    }

    /**
     * 使用的时候一定要找吴迪同步
     */
    public void setUpdateTime(long updateTime) {
        this.updateTime = updateTime;
    }

    public String getBackground() {
        return background;
    }

    public void setBackground(String background) {
        this.background = background;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getPicture(int pos) {
        if (pos == 0) {
            return avatarUrl;
        } else {
            return null;
        }
    }

    public String getPrevPicture(int pos) {
        if (pos == 0) {
            return avatarPrevUrl;
        } else {
            return null;
        }
    }

    public void setContact(ContactsModel contact) {
        this.contactModel = contact;
    }

    public ContactsModel getContact() {
        return contactModel;
    }

    public int getStatus_type() {
        return status_type;
    }

    public void setStatus_type(int status_type) {
        this.status_type = status_type;
    }

    public void setBaba(boolean isBaba) {
        this.isOnlyLocal = !isBaba;
    }

    public int isBabaForSort() {
        return isOnlyLocal ? 0 : 1;
    }

    public String getNameForSort() {
        if (null != contactModel) {
            return contactModel.getNameForSort();
        } else {
            return "+" + userId;
        }
    }

    /**
     * @return 以英文字母的形式返回名字
     */
    public String getSortAlpha() {
        if (null != contactModel) {
            return contactModel.getSortKey();
        } else {
            return "+" + userId;
        }
    }

    public boolean isBabaTeam() {
        return ContactUtil.isBabaTeam(userId);
    }

    public boolean isFileAssistant() {
        return ContactUtil.isFileAssistant(userId);
    }

    public boolean isSomaNews() {
        return ContactUtil.isSomaNews(userId);
    }

    public static String getTag() {
        return TAG;
    }

    public UserModel clone() {
        UserModel o = null;
        try {
            o = (UserModel) super.clone();
        } catch (Exception e) {
            VLog.e("TAG_LOG_ERROR", e);
        }
        return o;
    }

    @Override
    public String toString() {
        return "UserModel [userId=" + userId + ", alias=" + alias
                + ", nickName=" + nickName + ", avatarUrl=" + avatarUrl
                + ", countryCode=" + countryCode + ", countryPhone="
                + countryPhone + ", avatarPrevUrl=" + avatarPrevUrl + ", note="
                + note + ", updateTime=" + updateTime + ", background="
                + background + ", status=" + status + ", status_type="
                + status_type + ", isOnlyLocal=" + isOnlyLocal
                + ", contactModel=" + contactModel + "]";
    }

    public boolean isSymbol() {
        if (null != contactModel) {
            return contactModel.isSymbol();
        } else {
            return true;
        }
    }

    public boolean getIsArabic() {
        if (null != contactModel) {
            return contactModel.getIsArabic();
        } else {
            return false;
        }
    }

    public long getVipExpireDate() {
        return vipExpireDate;
    }

    public void setVipExpireDate(long vipExpireDate) {
        this.vipExpireDate = vipExpireDate;
    }

    public boolean isVip() {
        return isVip;
    }

    public void setVip(boolean vip) {
        isVip = vip;
    }

    public String getEmail(){
        return email;
    }

    public void setEmail(String email) {
        if (TextUtils.isEmpty(email)) {
            return;
        }
        this.email = email;
    }

    public void setBadgeWallet(Boolean badgeWallet, Long walletExpireTime) {
        if (mUserModelExtra == null) {
            mUserModelExtra = new UserModelExtra();
        }
        mUserModelExtra.isWallet = badgeWallet;
        if (walletExpireTime != null) {
            mUserModelExtra.walletExpireTime = walletExpireTime;
        }

        if (VLog.OPEN_LOG) {
            VLog.e("TAG_BADGE", "userId = %s,setBadgeWallet = %s,walletExpireTime = %s", userId + "", badgeWallet + "", walletExpireTime + "");
        }
    }

    public long getWalletExpireTime() {
        if (mUserModelExtra != null && mUserModelExtra.walletExpireTime != null) {
            return mUserModelExtra.walletExpireTime;
        }
        return 0L;
    }

    public boolean isBadgeWallet() {
        if (mUserModelExtra != null && mUserModelExtra.isWallet != null) {
            return mUserModelExtra.isWallet;
        }
        return false;
    }

    public boolean isFriend() {
        return true;//TODO:
    }

    public boolean isStranger() {
        return isStranger;
    }

    public void setStranger(boolean stranger) {
        isStranger = stranger;
    }

    public boolean isOaVerified() {
        return oaVerified;
    }

    public void setOaVerified(boolean verified) {
        oaVerified = verified;
    }

    public void setOaIcon(String oaIcon) {
        this.oaIcon = oaIcon;
    }

    public String getOaIcon() {
        return oaIcon;
    }

    public void setOaSubType(int oaSubType) {
        this.oaSubType = oaSubType;
    }

    public int getOaSubType() {
        return oaSubType;
    }

    public ContactsModel getContactModel() {
        return contactModel;
    }

    public boolean isOnlyLocal() {
        return isOnlyLocal;
    }


    public String getAvatarDisplayText() {
        return avatarDisplayText;
    }

    public void setAvatarDisplayText(String avatarDisplayText) {
        this.avatarDisplayText = avatarDisplayText;
    }

    public String getLastContactNameHash() {
        return lastContactNameHash;
    }

    public void setLastContactNameHash(String lastContactNameHash) {
        this.lastContactNameHash = lastContactNameHash;
    }

    public void encodeExtraData() {
        JSONObject jsonObject = new JSONObject();
        try {
            if (mUserModelExtra != null) {
                mUserModelExtra.buildJson(jsonObject);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        extraData = jsonObject.toString();
    }

    public void decodeExtraData() {
        JSONObject jsonObject;
        if (!TextUtils.isEmpty(extraData)) {
            try {
                jsonObject = new JSONObject(extraData);
                mUserModelExtra = UserModelExtra.fromJson(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    public String getExtraData() {
        return extraData;
    }

    public void setExtraData(String extraData) {
        this.extraData = extraData;
    }
}

